/**
 * 岗位选择器
 */
import React, { useEffect } from 'react';
import { Select } from 'antd';
import { getApplyPostList, getPostList } from '@/pages/Organization/OrgFlow/services';
import { useRequest } from '@/hooks';
import { connect } from 'umi';

/**
 *
 * @param user 当前用户
 * @param code organizationCode
 * @param value
 * @param status 1,启用 0,禁用
 * @param showChildDutyFlag 是否查询子级
 * @param onChange
 * @returns {*}
 * @constructor
 */
function Post({
    user,
    code,
    value,
    status = 1,
    showChildDutyFlag,
    onChange,
    disableFlag,
    extraQuery = {},
    excludeOptions = [],
    noAuth = false,
    ...rest
}) {
    const companyId = user?.firstOrgInfo?.firstCompanyCode;
    const service = noAuth ? getApplyPostList : getPostList;
    const { data: sourceData = [], run } = useRequest(params => service(params), {
        manual: true,
        formatResult: data => (Array.isArray(data.data) ? data.data : [])
    });

    useEffect(() => {
        const param = { status, ...extraQuery };
        if (code === null || code === undefined) {
            param.organizationCode = companyId;
        } else {
            param.organizationCode = code;
        }
        if (showChildDutyFlag) {
            param.showChildDutyFlag = showChildDutyFlag;
        }
        run(param);
    }, [code, companyId]);

    return (
        <>
            <Select
                style={{ width: 200 }}
                dropdownMatchSelectWidth={false}
                optionLabelProp="label"
                placeholder="请选择"
                showSearch
                optionFilterProp="children"
                allowClear
                getPopupContainer={triggerNode => triggerNode.parentElement}
                value={value}
                disabled={disableFlag}
                onChange={_value => {
                    onChange(_value);
                }}
                {...rest}
            >
                {sourceData
                    .filter(item => !excludeOptions.includes(item.dutyCode))
                    .map(item => (
                        <Select.Option value={item.dutyCode} key={item.id} label={item.dutyAlias}>
                            {item.dutyAlias}
                        </Select.Option>
                    ))}
            </Select>
            {disableFlag && (
                <div style={{ lineHeight: '20px', color: '#BFBFBF' }}>选择新组织机构后，才可选择新岗位</div>
            )}
        </>
    );
}

export default connect(({ user }) => ({ user: user.currentUser }))(Post);
